const app = getApp()
const util = require('../../utils/util.js')

Page({
  data: {
    //selfInfo只在exist为true时存在，只用于显示，插入user表时直接使用name，account
    loading: 1,
    exist: false,
    fromLogin: false, //新用户添加账号成功后为true
    confirm: false,
    remark: null,
    btnInvalid: false,
    noAccount: false, //当用户不是学生用户设为true
    stop: 0,
    invalidTitle: "未发现设备",
    invalidArea: "请确认您处于有效区域内！",
    locationContent: "请在系统设置-应用权限管理中开启允许微信使用地理位置的开关；\r\n\r\n若定位权限开启后仍出现此提示，请查看您的系统定位和WI-FI模块是否打开！",
  },

  onLoad: function(option) {
    // console.log(option)
    let meetingInfo = wx.getStorageSync("signInQr")
    if (option.login) {
      this.setData({
        fromLogin: true
      })
    }
    if (option.type) {
      meetingInfo.meetingId = meetingInfo.id
      meetingInfo.schoolId = app.globalData.departmentId

      wx.request({
        url: app.kaoqinUrl + '/WeChat/AttendanceSys/getBlueToothInfoByIds',
        method: 'POST',
        data: {
          ids: meetingInfo.blueToothList
        },
        dataType: 'json',
        success: res => {
          meetingInfo.meetingId = meetingInfo.id
          meetingInfo.blueToothList = res.data
          meetingInfo.schoolId = app.globalData.departmentId
          this.setData({
            meetingInfo: meetingInfo
          })
        }
      })
    }
    this.setData({
      meetingInfo: meetingInfo
    })

    console.log(this.data.meetingInfo)
    wx.request({
      url: app.kaoqinUrl + '/WeChat/weChatSystem/getSchoolUUIDS',
      method: 'POST',
      data: this.data.meetingInfo.schoolId,
      dataType: 'json',
      success: res => {
        this.setData({
          uuids: res.data.split(",")
        })
      }
    })

  },

  onShow: function() {
    let that = this

    //根据weChatId查询用户是否已经签到 未签到再查询是否已经存在
    wx.request({
      url: app.kaoqinUrl + '/WeChat/AttendanceSys/isContainInSignList',
      method: "POST",
      data: {
        meetingId: this.data.meetingInfo.meetingId,
        weChatId: app.globalData.wechatId
      },
      success: res => {
        console.log(res)
        if (res.data.res == 'EXIST') {
          wx.setStorageSync("personalSignInInfo", res.data.data)
          wx.redirectTo({
            url: '/pages/signInSuccess/signInSuccess?repeat=1',
          })

        } else {
          wx.request({
            url: app.kaoqinUrl + '/WeChat/AttendanceSys/getUserInfoByWeChatId?weChatId=' + app.globalData.wechatId,
            success: res => {
              // wx.hideLoading()
              if (res.data) {
                console.log(res.data)
                this.setData({
                  exist: true,
                  selfInfo: {
                    name: res.data.realName,
                    account: res.data.phone
                  }
                })
              }
              this.setData({
                noAccount: [1, 3].indexOf(that.data.meetingInfo.type) == -1 ? true : false
              })
            },
            fail: () => {
              wx.showToast({
                title: '获取用户数据失败！',
                icon: "none",
                mask: true
              })
            },
            complete: () => {
              this.setData({
                loading: 0
              })
            }
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取签到信息失败！',
          icon: "none",
          mask: true
        })
      }
    })

    this.setData({
      stop: 0
    })
  },

  onHide: function() {
    this.setData({
      stop: 1
    })
    wx.stopBeaconDiscovery()
  },


  onUnload: function() {
    this.setData({
      stop: 1
    })
    wx.stopBeaconDiscovery()
  },

  inputName: function(e) {
    this.setData({
      name: app.trimAll(e.detail.value)
    })
  },
  inputAccount: function(e) {
    this.setData({
      account: app.trimAll(e.detail.value)
    })
  },
  inputRemark: function(e) {
    this.setData({
      remark: app.trim(e.detail.value)
    })
  },

  checkStatus: function() {
    let comfirm = this.data.confirm == false ? true : false
    this.setData({
      confirm: comfirm
    })
  },

  formSubmit: util.throttle(function() {
    // wx.reLaunch({
    //   url: '/pages/signInSuccess/signInSuccess',
    // })
    // return

    if (this.data.btnInvalid) return

    this.setData({
      btnInvalid: true
    })

    let that = this
    if (that.data.exist) {
      //user已存在 判断是否需要名单 1,2查询 3,4直接提交）
      console.log("EXIST")
      wx.showLoading({
        title: '正在提交数据',
        mask: true
      })
      if ([1, 2].indexOf(that.data.meetingInfo.type) != -1) {
        let account
        that.data.meetingInfo.type == 2 ?
          account = "BBBABAAA" :
          account = app.globalData.identityId == -2 ? that.data.selfInfo.account : "BBBABAAA"
        wx.request({
          url: app.kaoqinUrl + '/WeChat/AttendanceSys/getOriginalMemberListByNameAccount',
          method: "POST",
          data: {
            name: that.data.selfInfo.name,
            account: account,
            groupNameId: that.data.meetingInfo.groupNameId,
            type: that.data.meetingInfo.type
          },
          success: (res) => {
            console.log(res)
            if (res.data.res == 'success') {
              that.search()
            } else {
              wx.hideLoading()
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
              })
              that.setData({
                btnInvalid: false
              })
            }
          }
        })
      } else {
        that.search()
      }


    } else if ((!that.data.exist && !that.data.noAccount && (!that.data.account || !that.data.name)) ||
      (!that.data.exist && that.data.noAccount && !that.data.name)) {
      //先判断有无输入
      //需要输信息 且需要学号 两个都不能为空
      //需要输信息 不需要学号 名字不为空
      console.log("NOT EXIST")
      console.log(that.data.account)
      console.log(that.data.name)
      wx.showToast({
        title: '请输入必填信息',
        image: '/images/warning.png',
        mask: true
      })
      that.setData({
        btnInvalid: false
      })
    } else {
      console.log("NOT EXIST ADD USER")
      //输入信息 提交到user表 但先判断是否需要按照名单 
      //有名单的 先判断有无权限 无权限不插入user
      wx.showLoading({
        title: '正在提交数据',
        mask: true
      })
      let reqData = {
        //name需要和导入的excel比对
        name: that.data.name,
        account: that.data.account ? that.data.account : "BBBABAAA",
        weChatId: app.globalData.wechatId,
        departMentId: that.data.meetingInfo.schoolId,
        groupNameId: that.data.meetingInfo.groupNameId,
        type: that.data.meetingInfo.type
      }
      console.log(reqData)
      wx.request({
        url: app.kaoqinUrl + '/WeChat/AttendanceSys/addUserInfo',
        method: 'POST',
        data: reqData,
        success: res => {
          wx.hideLoading()
          //根据type判断有无权限
          if (res.data.res == "fail") {
            wx.showModal({
              content: res.data.msg,
              showCancel: false,
            })
            that.setData({
              btnInvalid: false
            })
          } else {
            //user已插入  签到搜索蓝牙
            that.setData({
              exist: true,
              selfInfo: {
                name: reqData.name,
                account: reqData.account
              }
            })
            that.search()
          }
        },
        fail: () => {
          wx.showToast({
            title: '服务器异常',
            image: '/images/warning.png',
            mask: true
          })
          that.setData({
            btnInvalid: false
          })
        }
      })
    }
  }),

  search: function() {
    let that = this
    this.setData({
      find: 0,
      waitIter: 0
    })

    // !!!!!!!!!!!!!!!!!!!!!!!!!测试!!!!!!!!!!!!!!!!!!!!
    //
    //
    // wx.request({
    //   url: app.baseUrl + '/AttendanceSys/addSignInRecord',
    //   method: "POST",
    //   dataType: "text",
    //   data: {
    //     name: that.data.selfInfo.name,
    //     account: that.data.selfInfo.account,
    //     remark: that.data.remark,
    //     weChatId: app.globalData.wechatId,
    //     meetingId: that.data.meetingInfo.meetingId,
    //     type: that.data.meetingInfo.type,
    //   },
    //   success: res => {
    //     if ('success' == res.data) {
    //       wx.setStorageSync("personalSignInInfo", {
    //         name: that.data.selfInfo.name,
    //         account: that.data.selfInfo.account
    //       })
    //       if (that.data.fromLogin) {
    //         wx.reLaunch({
    //           url: '/pages/signInSuccess/signInSuccess',
    //         })
    //       } else {
    //         wx.redirectTo({
    //           url: '/pages/signInSuccess/signInSuccess',
    //         })
    //       }

    //     } else if ('fail' == res.data) {
    //       wx.hideLoading()
    //       wx.showModal({
    //         content: '当前签到还未开始，请耐心等待！',
    //         showCancel: false
    //       })
    //     }
    //   },
    //   fail: () => {
    //     wx.showToast({
    //       title: '添加签到记录异常',
    //       icon: "none",
    //       mask: true
    //     })
    //   },
    //   complete: () => {
    //     that.setData({
    //       btnInvalid: false
    //     })
    //   }
    // })
    // return
    //
    //
    // !!!!!!!!!!!!!!!!!!!!!!!!!测试!!!!!!!!!!!!!!!!!!!!



    if (wx.openBluetoothAdapter) {

      wx.showLoading({
        title: '正在搜索设备',
        mask: true
      })

      wx.openBluetoothAdapter({
        //开启蓝牙
        fail(res) {
          wx.showToast({
            title: "请开启蓝牙",
            image: "/images/warning.png",
            duration: 2000
          })
          that.setData({
            btnInvalid: false
          })
        },
        success(res) {

          wx.getLocation({
            type: 'wgs84',
            fail: (res) => {
              //不允许打开定位
              wx.hideLoading()
              wx.getSetting({
                success(res) {
                  //开启小程序内定位
                  if (res.authSetting["scope.userLocation"] == false) {
                    wx.showToast({
                      title: "请允许小程序使用地理位置功能！您可以在本页面右上角点击【设置】按钮进行授权。",
                      icon: "none",
                      mask: true,
                      duration: 2000
                    })
                  } else {
                    //开启系统设置定位
                    wx.getSystemInfo({
                      success: res => {
                        if (res.platform == "ios") {
                          that.setData({
                            locationContent: "请在系统设置-微信里开启允许微信使用地理位置的开关"
                          })
                        }
                        wx.showModal({
                          title: '未允许使用地理位置',
                          content: that.data.locationContent,
                          showCancel: false
                        })
                      },
                      fail: res => {
                        wx.showModal({
                          title: '未允许使用地理位置',
                          content: that.data.locationContent,
                          showCancel: false
                        })
                      }
                    })
                  }
                },
                complete: () => {
                  that.setData({
                    btnInvalid: false
                  })
                }
              })
            },
            success: res => {
              //允许打开定位
              wx.startBeaconDiscovery({
                uuids: that.data.uuids,
                // uuids: ["00001803-494c-4f47-4943-544543480000"],
                success(res) {
                  let search = 0

                  function doSearch() {
                    search++
                    console.log(search)
                    if (!that.data.stop) {
                      if (search > 12) {
                        that.showModalOwn()
                      } else {
                        setTimeout(doSearch, 900)
                      }
                    }
                  }
                  doSearch()

                  wx.onBeaconUpdate(function(res) {
                    //加判断条件
                    console.log(res.beacons)
                    if (res.beacons.length && search <= 12 && that.data.waitIter == 0) {
                      that.setData({
                        waitIter: 1
                      })
                      for (let i = 0; i < res.beacons.length; i++) {
                        for (let j = 0; j < that.data.meetingInfo.blueToothList.length; j++) {
                          // console.log(that.data.meetingInfo.blueToothList[j])
                          if (that.data.meetingInfo.blueToothList[j].major == res.beacons[i].major && that.data.meetingInfo.blueToothList[j].minor == res.beacons[i].minor) {
                            that.setData({
                              find: 1,
                              stop: 1
                            })
                            wx.stopBeaconDiscovery()
                            break
                          }
                        }
                        // meetingInfo.blueToothList,格式[{major: ,minor: },{}]
                        if (that.data.find == 1) {
                          //提交数据到签到表
                          wx.request({
                            url: app.kaoqinUrl + '/WeChat/AttendanceSys/addSignInRecord',
                            method: "POST",
                            dataType: "text",
                            data: {
                              name: that.data.selfInfo.name,
                              account: that.data.selfInfo.account,
                              remark: that.data.remark,
                              weChatId: app.globalData.wechatId,
                              meetingId: that.data.meetingInfo.meetingId,
                              type: that.data.meetingInfo.type,
                            },
                            success: res => {
                              if ('success' == res.data) {
                                wx.setStorageSync("personalSignInInfo", {
                                  name: that.data.selfInfo.name,
                                  account: that.data.selfInfo.account
                                })
                                if (that.data.fromLogin) {
                                  wx.reLaunch({
                                    url: '/pages/signInSuccess/signInSuccess',
                                  })
                                } else {
                                  wx.redirectTo({
                                    url: '/pages/signInSuccess/signInSuccess',
                                  })
                                }

                              } else if ('fail' == res.data) {
                                wx.hideLoading()
                                wx.showModal({
                                  content: '当前签到还未开始，请耐心等待！',
                                  showCancel: false
                                })
                              }
                            },
                            fail: () => {
                              wx.showToast({
                                title: '添加签到记录异常',
                                icon: "none",
                                mask: true
                              })
                            },
                            complete: () => {
                              that.setData({
                                btnInvalid: false
                              })
                            }
                          })
                          return
                        }
                      }
                      that.setData({
                        waitIter: 0
                      })
                    }
                  })
                },
                fail(res) {
                  that.showModalOwn()
                }
              })
            },
          })
        }
      })

    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
      that.setData({
        btnInvalid: false
      })
    }

  },


  openSetting() {
    wx.openSetting()
  },


  showModalOwn: function() {
    let that = this
    wx.hideLoading()
    wx.stopBeaconDiscovery()
    wx.showModal({
      title: that.data.invalidTitle,
      content: that.data.invalidArea,
      showCancel: false
    })
    this.setData({
      btnInvalid: false
    })
  }
})